package com.quik.web.action.ac;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.quik.backend.service.account.AcService;
import com.quik.common.Constants;
import com.quik.entity.SysAccount;
import com.quik.entity.SysRoleRight;
import com.quik.exception.ErrorCode;
import com.quik.web.action.BaseAction;

@Controller
@RequestMapping("/portal")
@SuppressWarnings("unchecked")
public class PortalAction extends BaseAction {

	private static Logger log = Logger.getLogger(PortalAction.class);

	@Autowired
	private AcService acService;

	@RequestMapping(value = "main", method = RequestMethod.GET)
	public ModelAndView main(HttpServletRequest request) {
		try {
			this.getLoginAccount(request);
			ModelAndView mav = new ModelAndView("/portal/main");
			List<SysRoleRight> rights = (List<SysRoleRight>) request
					.getSession().getAttribute(Constants.SESSION_AC);
			mav.addObject("rights", rights);
			return mav;
		} catch (Exception e) {
			log.error("Error: " + e.getMessage(), e);
			return this.processModelAndViewOnException(e);
		}
	}

	@RequestMapping(value = "login")
	public ModelAndView login() {

		try {
			ModelAndView mav = new ModelAndView("/portal/login");
			List<Object> classesList = new ArrayList<Object>(0);
			mav.addObject("classesList", classesList);
			return mav;
		} catch (Exception e) {
			log.error("Error: " + e.getMessage(), e);
			return this.processModelAndViewOnException(e);
		}

	}

	@RequestMapping(value = "submitToLogin", method = RequestMethod.POST)
	public ModelAndView submitForLogin(String loginUser, String password,
			String classes, HttpServletRequest request) {
		ModelAndView mav = new ModelAndView("redirect:/portal/main");

		try {
			SysAccount account = acService.login(loginUser, password);
			account.setClasses(classes);
			request.getSession().setAttribute(Constants.SESSION_ACCOUNT,
					account);
			List<SysRoleRight> rights = this.acService
					.findRoleRightByUser(account);
			request.getSession().setAttribute(Constants.SESSION_AC, rights);
		} catch (Exception e) {
			log.error("Error: " + e.getMessage(), e);
			return this.processModelAndViewOnException(e);
		}

		return mav;
	}

}
